package token

import (
	"gitee.com/wuzheng0709/backend-gopkg/infrastructure/config"
	"gitee.com/wuzheng0709/backend-gopkg/infrastructure/connector/redis"
	"gitee.com/wuzheng0709/backend-gopkg/infrastructure/pkg/gin/log"
	tmpJwt "gitee.com/wuzheng0709/backend-gopkg/infrastructure/pkg/jwt"
	"gitee.com/wuzheng0709/backend-gopkg/infrastructure/pkg/toolfunc"
	"net/url"
	"time"

	"github.com/golang-jwt/jwt/v4"
)

var _ Token = (*token)(nil)

type Token interface {
	// i 为了避免被其他包实现
	i()

	// JwtSign 签名
	JwtSign(userId int64, userName string, expireDuration time.Duration) (tokenString string, err error)

	// JwtParse 解密
	JwtParse(tokenString string) (*claims, error)

	// UrlSign URL 签名方式，不支持解密
	UrlSign(path string, method string, params url.Values) (tokenString string, err error)
}

type token struct {
	secret string
}

type claims struct {
	UserID   int64
	UserName string
	jwt.StandardClaims
}

func New(secret string) Token {
	return &token{
		secret: secret,
	}
}

func (t *token) i() {}

func GenerateTokenForUserId(userId string) string {
	//颁发token
	token, err := tmpJwt.CreateToken(userId)
	if err != nil {
		log.Error("生成token失败")
		return ""
	}
	//token存进cache
	var fields = make(map[string]interface{}, 10)
	fields["user_id"] = toolfunc.String2Int64(userId)
	fields["platform"] = ""
	fields["device_id"] = ""
	fields["device_name"] = ""
	_, err = redis.BatchHashSet(redis.ImRedisDB, "access_token_"+token, fields, config.C.Jwt.TimeOut*time.Hour)
	return token
}
